import { connect } from 'umi';
import { Spin, message } from 'antd';
import { useEffect, useState } from 'react';
import '../common/style.less';
import { GetPurchasingMethodChangeServices, syncPDFtoOAServices } from '../services/UpdateServices';
import { ChangeControllerContext } from '../common/useOAContext';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { getInvoiceCode, getPersonalInfo, getPosIDs, getTenantID, getUserID, renderWaterMarkDom } from '@/utils';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { BGflowBusinessType, FSBG_STATE_CG, FSBG_STATE_QC, FSBG_STATE_SHZ } from '../common/Format';
import {
  AddfailureChangeServices,
  alterApplyChangeStateServices,
  editPackProcureRealServices,
  updatePackFlagServices,
} from '../../ApplyManage/services/UpdateService';
import { ILoadMapTypeAll } from '@/common';
import { SHTG_CHECKSTATE, SHZ_CHECKSTATE, setOAMessageSev } from '../../Acommon';

const DetailInfoViewOA: React.FC<Record<string, any>> = ({ locationProps, curRes }) => {
  /** 样式根名称 */
  const prefix = 'purchase-change-update-';

  /** 保存详情 */
  const [infoObj, setInfoObj] = useState<Record<string, any>>({});

  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  const [iseditReal, setIseditReal] = useState(false); // 是否调用更改标包拟采方式

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});

  /** 获取详情 */
  const { GetPurchasingMethodChangeRun, GetPurchasingMethodChangeLoading, reloadDetailInfo } = GetPurchasingMethodChangeServices((res: any) => {
    if (res && res?.msgFlag) {
      message?.success(res?.msg);
      setInfoObj(res?.obj);
      if (res?.obj?.state == FSBG_STATE_SHZ() && res?.obj?.checkState == SHZ_CHECKSTATE()) {
        setIseditReal(true);
      }

      // 做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1002`]) {
        let workFlowNode = infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1002`];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          setOAMessageRun({
            // 已读未办
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      GetPurchasingMethodChangeRun({ id: locationProps?.state?.id });
    }
  }, [locationProps?.state?.id]);

  // 初始化水印
  // useEffect(() => {
  //   renderWaterMarkDom('methodChangeOAPage-divBox', true);
  //   return () => {
  //     renderWaterMarkDom('methodChangeOAPage-divBox', false);
  //   };
  // }, []);

  /** <<<================================改变【变更采购申请】工单状态的services================================>>> */
  const { alterApplyChangeStateChangeRun, alterApplyChangeStateLoading } = alterApplyChangeStateServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    }
  });

  /** <<<================================实施流标 - 添加实施================================>>> */
  const { AddfailureChangeRun, AddfailureChangeLoading } = AddfailureChangeServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      alterApplyChangeStateChangeRun({
        applyCompanyID: infoObj?.applyCompanyID,
        applyDepartmentID: infoObj?.applyDepartmentID,
        applyPositionID: infoObj?.applyPositionID,
        applyerID: infoObj?.applyerID,
        state: FSBG_STATE_CG(),
        id: infoObj?.id,
        versionNum: infoObj?.versionNum,
      });
    }
  });

  /** <<<================================改变标包拟采方式Services================================>>> */
  const { editPackProcureRealChangeRun, editPackProcureRealChangeLoading } = editPackProcureRealServices((res) => {
    if (res?.msgFlag) {
      alterApplyChangeStateChangeRun({
        applyCompanyID: infoObj?.applyCompanyID,
        applyDepartmentID: infoObj?.applyDepartmentID,
        applyPositionID: infoObj?.applyPositionID,
        applyerID: infoObj?.applyerID,
        state: FSBG_STATE_CG(),
        id: infoObj?.id,
        versionNum: infoObj?.versionNum,
      });
    }
  });

  /** 修改采购分包是否变更状态接口 */
  const { updatePackFlagRun, updatePackFlagLoading } = updatePackFlagServices((res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  });

  /** 审核中，审核通过/作废 开关 */
  const [isSHTGFlag, setIsSHTGFlag] = useState(false);

  /** 监听数据状态改变，更改状态 */
  useEffect(() => {
    if (infoObj?.state && infoObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1001` && infoObj?.checkState == SHZ_CHECKSTATE()) {
      setIsSHTGFlag(true);
    }
    if (
      isSHTGFlag &&
      (infoObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1002` ||
        infoObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1003`)
    ) {
      // 修改采购分包是否变更状态接口
      updatePackFlagRun({
        changeID: infoObj?.id,
        changeFlag: 0,
      });
    }
  }, [infoObj?.state, infoObj?.checkState]);

  /** 同步审核记录给档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {});
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList =
      infoObj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1002`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /** 在审核通过后自动触发更改拟采方式接口 */
  useEffect(() => {
    if (infoObj?.checkState == SHTG_CHECKSTATE() && infoObj?.state == FSBG_STATE_CG()) {
      if (iseditReal) {
        if (infoObj?.difFlag == 1) {
          setIseditReal(false);
          AddfailureChangeRun({
            id: infoObj?.sourceID,
            procureDraft: infoObj?.procureDraft,
            procureReal: infoObj?.procureReal,
            ownPhone: getPersonalInfo()?.phoneMobile,
            sourceCode: getInvoiceCode('SS'),
          });
        } else {
          setIseditReal(false);
          editPackProcureRealChangeRun({
            procureOrg: infoObj?.procureOrg,
            id: infoObj?.packID,
            procureReal: infoObj?.procureReal,
          });
        }
        syncPDFtoOARunfun(infoObj); //推送信息至档案
      }
    }
  }, [iseditReal, infoObj]);

  return (
    <ChangeControllerContext.Provider
      value={{
        styleFixCls: prefix,
        infoObj,
        reloadDetail: reloadDetailInfo,
        invalidState,
        setInvalidState,
        curRes,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
      }}
    >
      <Spin
        spinning={
          GetPurchasingMethodChangeLoading ||
          setOAMessageLoaidng ||
          alterApplyChangeStateLoading ||
          updatePackFlagLoading ||
          AddfailureChangeLoading ||
          editPackProcureRealChangeLoading ||
          syncPDFtoOALoading
        }
      >
        <div className={`${prefix}infoViewOA`} id={'methodChangeOAPage-divBox'}>
          <DetailInfoTopViewOA />
          <DetailInfoCenterViewOA />
          <DetailInfoBottomViewOA />
        </div>
      </Spin>

      {invalidState?.isShow && (
        <RevokeModal
          resObj={invalidState?.resObj}
          revokeRequestUrl={'/purchaseSourceChangeController/invalid'}
          onClose={() => setInvalidState({})}
          reqBody={{ state: FSBG_STATE_QC() }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.packName}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={reloadDetailInfo}
        />
      )}
    </ChangeControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
